import React, { useEffect, useState } from 'react';
import BottomNavigation from '@material-ui/core/BottomNavigation';
import BottomNavigationAction from '@material-ui/core/BottomNavigationAction';
import './tabbar.less'

// 把图片引进来
import home from '../../assets/images/tabbar/home_2.png'
import homeActive from '../../assets/images/tabbar/home_1.png'
import fast from '../../assets/images/tabbar/fast.png'
import user from '../../assets/images/tabbar/my_2.png'
import userActive from '../../assets/images/tabbar/my_1.png'
import { useHistory } from 'react-router-dom';

// 如果判断里面是判断数字进行操作，可以把数据抽取出来变成一个数组
const routers = ['/home', '/fast', '/user']

export default function TabBar(props) {
    // 定义一个决定 tabbar是否显示的变量
    const [isShow, setIsShow] = useState(true)
    const [value, setValue] = useState(0);
    // 在函数组件里面，使用 useHistory 就可以得到路由对象，
    const history = useHistory()

    // 进行刷新后的 value 的值的重新修改
    useEffect(() => {
        // switch (history.location.pathname) {
        //     case '/home':
        //         setValue(0)
        //         break;
        //     case '/fast':
        //         setValue(1)
        //         break;
        //     case '/user':
        //         setValue(2)
        //         break;
        // }
        const index = routers.indexOf(history.location.pathname)
        setValue(index)
        setIsShow(index !== -1) // 控制tabbar在不同页面下的显示和隐藏
        
    }, [history.location.pathname])

    const changeFn = (e, v) => {
        // console.log(newValue);
        setValue(v);
        // 跳转
        // console.log(history);
        // switch (newValue) {
        //     case 0:
        //         history.push('/home')
        //         break;
        //     case 1:
        //         history.push('/fast')
        //         break;
        //     case 2:
        //         history.push('/user')
        //         break;
        // }
        history.push(routers[v])
    }
    return (
        <BottomNavigation
            style={{ display: isShow ? 'flex' : 'none' }}
            className="tab-bar"
            value={value}
            onChange={changeFn}
            showLabels
        >
            <BottomNavigationAction label="首页" icon={<img alt="" src={value === 0 ? homeActive : home} />} />
            <BottomNavigationAction label="快速刷题" icon={<img alt="" src={fast} />} />
            <BottomNavigationAction label="我的" icon={<img alt="" src={value === 2 ? userActive : user} />} />
        </BottomNavigation>
    );
}
